package 数据结构;

import org.junit.Test;

import java.util.*;

public class StockPrice {
    private Map<Integer,Integer>  map;  //key是timestamp val是price
    private TreeMap<Integer,Integer>  tree; //key是price val是价格出现的次数
    private int maxStamp;
    public StockPrice() {
        map=new HashMap<Integer,Integer>();
//    看到这种查询最大最小值，就要快速想到 TreeMap 这种，可查询最大最小值的数据结构。
        tree=new TreeMap<Integer,Integer>();
        maxStamp=-1;
    }

    public void update(int timestamp, int price) {
        if(map.containsKey(timestamp))
        {
            int oldPrice=map.get(timestamp);
            //旧价格只出现一次,直接删除
            if(tree.get(oldPrice)==1)
                tree.remove(oldPrice);
            else
                tree.put(oldPrice,tree.get(oldPrice)-1);

            //判断tree中是否已经存在新的price
            if(tree.containsKey(price))
                tree.put(price,tree.get(price)+1);
            else
                tree.put(price,1);
            map.put(timestamp,price);
        }
        else
        {
            maxStamp=Math.max(maxStamp,timestamp);
            if(tree.containsKey(price))
                tree.put(price,tree.get(price)+1);
            else
                tree.put(price,1);
            map.put(timestamp,price);
        }
    }

    public int current() {
        return map.get(maxStamp);
    }

    public int maximum() {
        return tree.lastKey();
    }

    public int minimum() {
        return tree.firstKey();
    }
}
